library(effects)
library(tidyverse)
library(stargazer)
library(gridExtra)

setwd("~/Dropbox/projects/inseparability/replication")
study3 <- read_csv("study3.csv")

cbPalette <- c("#E69F00", "#0072B2")

study3 <- study3[study3$gc == 1,]
study3 <- study3[!is.na(study3$Q63_2),]

#recode leaners
study3$Q9[study3$Q10==1] <- 1
study3$Q9[study3$Q10==2] <- 2

#recode reference levels
study3$treatment[study3$treatment=="negative"] <- "Negative Result"
study3$treatment[study3$treatment=="positive"] <- "Positive Result"
study3$treatment <- as.factor(study3$treatment)
#study3$treatment <- relevel(study3$treatment, 2) 

study3$round3.race <- as.factor(study3$round3.race)
study3$round3.race <- relevel(study3$round3.race, 2) 
study3$pid <- study3$Q9

#filter out pure idependents
study3 <- study3[study3$pid <=2,]

study3$pid<-recode(study3$pid, "1" = "Democrat", "2" = "Republican")
study3$pid <- as.factor(study3$pid)


study3$race <- NA
study3$race[study3[,"Q5"]==1] <- "White"
study3$race[study3[,"Q5"]==2] <- "Black"

study3$race <- as.factor(study3$race)

study3$affectivepolarization <- NA
study3$inparty <- NA
study3$outparty <- NA

study3$inparty[which(study3$pid=="Democrat")] <- study3$Q200_2[which(study3$pid=="Democrat")]
study3$inparty[which(study3$pid=="Republican")] <- study3$Q63_2[which(study3$pid=="Republican")]

study3$outparty[which(study3$pid=="Republican")] <- study3$Q200_2[which(study3$pid=="Republican")]
study3$outparty[which(study3$pid=="Democrat")] <- study3$Q63_2[which(study3$pid=="Democrat")]

study3$affectivepolarization <- study3$inparty - study3$outparty

study3$racepolarization <- NA

summary(lm(affectivepolarization~treatment, data=study3))

study3$inrace <- NA
study3$outrace <- NA

study3$inrace[which(study3$race=="Black")] <- study3$Q202_2[which(study3$race=="Black")]
study3$inrace[which(study3$race=="White")] <- study3$Q201_2[which(study3$race=="White")]

study3$outrace[which(study3$race=="White")] <- study3$Q202_2[which(study3$race=="White")]
study3$outrace[which(study3$race=="Black")] <- study3$Q201_2[which(study3$race=="Black")]
study3$outrace[is.na(study3$outrace)] <-50
study3$racepolarization <- study3$inrace - study3$outrace

######################
# Manipulation Check
######################

#recode to handle a skipped number in the qualtrics value recode
study3$Q199[study3$Q199==4] <- 3
study3$Q199[study3$Q199==5] <- 4
t.test(Q199~treatment, data=study3)

######################
# Average Spillover
######################

df <- data.frame(group=character(),
				 mean=double(),
				 lower=double(),
				 upper=double(),
				 stringsAsFactors=FALSE)

tspill_race <- t.test(study3$outrace~study3$treatment)
tmain <- t.test(study3$outparty~study3$treatment)

32.01230       -               52.20978 
55.63982              -        62.34348 
6.7/8.67

format_ttest <- function(df, t, n){
	df[nrow(df)+1,] <- c(n, as.numeric(t$estimate[1] - t$estimate[2]), t$conf.int[1],t$conf.int[2])
	df$mean <- as.numeric(df$mean)
	df$upper <- as.numeric(df$upper)
	df$lower <- as.numeric(df$lower)
	return(df)
	
}

df <- format_ttest (df, tspill_race, "Parallel updating:\nout-racial affect")
df <- format_ttest (df, tmain, "Out-partisan affect")
df$group <- as.factor(df$group)
df$group <- factor(df$group,levels(df$group)[c(2,1)])

df

(race_ate <- ggplot(df,aes(y=mean,x=group))+
		geom_point()+
		geom_linerange(aes(ymin=lower,ymax=upper))+
		ylim(-30,2)+
		theme_bw()+
		ylab("Difference in mean feeling toward the \nout-group between negative and positive treatments")+
		xlab("") + 
		ggtitle("C: Study 3 (Partisan Treatment)") + 
		geom_hline(yintercept=0, linetype="dashed") + 
		theme(panel.spacing = unit(1, "lines")) + 
		theme(panel.grid.major = element_line(colour = "white"),panel.grid.minor = element_line(colour = "white"), axis.title.x = element_text(vjust=-0.5)) +
		coord_flip())

ggsave(plot=race_ate,"party_ate.eps", device="eps",width=5, height=1.75)


######################
# Reinforcement
######################

affpol <- lm(outparty~treatment*round3.race+race+pid, data=study3)
racepol <- lm(outrace~treatment*round3.race+race+pid, data=study3)

stargazer(affpol,racepol,covariate.labels=c("Positive Treatment","Player 1 Race - Black", "Participant Race - White", "Participant PID - Republican", "Positive Treatment X Player 1 Race Black"), dep.var.labels = c("Out Party Affect", "Out Race Affect"), omit.stat = c("f", "ser"), ci=T, star.cutoffs = c(0.05, 0.01, 0.001), type="text")

######################
# Diff-in-diff
######################

t.test(study3$racepolarization~study3$treatment)
t.test(study3$affectivepolarization~study3$treatment)
7.349057            -          3.705128 
36.29754            -          22.38043 

######################
# Out-group activation
######################

aligned <- lm(outrace~treatment, data= study3[(study3$race=="Black" & study3$pid == "Democrat") | (study3$race!="Black" & study3$pid == "Republican"),])
not <- lm(outrace~treatment, data= study3[(study3$race=="Black" & study3$pid == "Republican") | (study3$race!="Black" & study3$pid == "Democrat"),])

confint(aligned)
confint(not)
stargazer(aligned, not, covariate.labels=c("Positive Treatment"), dep.var.labels = c("Out Race Affect"), omit.stat = c("f", "ser"), ci=T, star.cutoffs = c(0.05, 0.01, 0.001), column.labels = c("Aligned Out-Groups", "Unaligned Out-Groups"))

study3$aligned <- "not"
study3$aligned[(study3$race=="Black" & study3$pid == "Democrat") | (study3$race!="Black" & study3$pid == "Republican")] <- "yes"

inter <- lm(outrace~treatment*aligned, data=study3)
summary(inter)
confint(inter)


###########
# Mechanism
###########

df <- data.frame(group=character(),
				 mean=double(),
				 lower=double(),
				 upper=double(),
				 stringsAsFactors=FALSE)

op_aligned <-t.test(outrace~treatment, data=study3[study3$aligned == "yes",])
op_unaligned <- t.test(outrace~treatment, data=study3[study3$aligned != "yes",])

model <- lm(outparty~treatment*aligned, data=study3)
confint(model)
df <- format_ttest (df, op_aligned, "Sorted Out-Groups")
df <- format_ttest (df, op_unaligned, "Cross-Cutting Out-Groups")
df$group <- as.factor(df$group)
df$group <- factor(df$group,levels(df$group)[c(2,3,1)])

df

(party_mech <- ggplot(df,aes(y=mean,x=group))+
		geom_point()+
		geom_linerange(aes(ymin=lower,ymax=upper))+
		ylim(-30,1)+
		theme_bw()+
		ylab("(Thermometer Points)\nDifference in mean feeling between negative \nand positive treatments")+
		xlab("") + 
		ggtitle("C: Study 3 (Partisan Treatment)") +
		geom_hline(yintercept=0, linetype="dashed") + 
		theme(panel.spacing = unit(1, "lines")) + 
		theme(panel.grid.major = element_line(colour = "white"),panel.grid.minor = element_line(colour = "white"), axis.title.x = element_text(vjust=-0.5)) +
		coord_flip())

ggsave(plot=party_mech,"party_mech.eps", device="eps",width=5, height=1.5)

######
# Halo
######

df <- data.frame(group=character(),
				 mean=double(),
				 lower=double(),
				 upper=double(),
				 stringsAsFactors=FALSE)

racediff<-t.test(study3$racepolarization~study3$treatment)
partydiff<-t.test(study3$affectivepolarization~study3$treatment)

df <- format_ttest (df, partydiff, "Party Difference\n (In - Out)")
df <- format_ttest (df, racediff, "Race Difference\n(In - Out)")
df$group <- as.factor(df$group)
df$group <- factor(df$group,levels(df$group)[c(2,3,1)])

df

####################
# HET
####################

white <- lm(outrace~treatment,data = study3[study3$race == "White",])
black <- lm(outrace~treatment,data = study3[study3$race != "White",])

democrat <- lm(outrace~treatment, data = study3[study3$pid == "Democrat",])
republican  <- lm(outrace~treatment, data = study3[study3$pid != "Democrat",])

stargazer(white, black, democrat, republican, covariate.labels=c("Positive Treatment"), dep.var.labels = c("Spillover to Out Race Affect"), omit.stat = c("f", "ser"), ci=T, star.cutoffs = c(0.05, 0.01, 0.001), column.labels = c("Whites", "Blacks", "Democrats", "Republicans"), type = "latex")

####### 
# reported race
#######

study3$same <- "Different"
study3$same[study3$round3.race == study3$race] <- "Same"

affpol <- lm(outparty~treatment*same+pid, data=study3)
racepol <- lm(outrace~treatment*same+pid, data=study3)

stargazer(racepol, affpol,  covariate.labels = c("Positive Treatment","Player 1 and Participant Same Race", "Participant Party - Republican", "Positive Treatment X Player 1 and Participant Same Race","(intercept)"), omit.stat = c("f", "ser"), ci=F, star.cutoffs = c(0.05, 0.01, 0.001), column.labels = c("Out-Race Affect", "Out-Party Affect"), type = "latex")
